package com.zxy;
import java.util.Scanner;

public class MaxSubarray {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入数组长度：");
        int n = scanner.nextInt();
        int[] nums = new int[n];
        System.out.println("请输入数组：");
        for (int i = 0; i < n; i++) {
            nums[i] = scanner.nextInt();
        }
        System.out.println("暴力法：");
        System.out.println(maxSubArray1(nums));
        System.out.println("动态规划：");
        System.out.println(maxSubArray2(nums));
    }
    //    暴力法
    public static int maxSubArray1(int[] nums) {

        int result = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                result = Math.max(result, sum);
            }
        }
        return result;
    }
    //动态规划
    public static int maxSubArray2(int [] nums){
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int result = dp[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(nums[i], dp[i-1] + nums[i]);
            result = Math.max(result, dp[i]);
        }
        return result;
    }
}
